# -*- encoding:utf8 -*-
from django.utils import timezone
from attendance.models import AvaiLeave,LeaveModel,LeaveApplication
from django.db.models import F
from attendance.tool_func import get_or_none
# from leave_ope import leave_span
from attendance.convert import dt2str,date2str,str2dt,t2day,t2h
from staff.models import StaffInfo
import json
from datetime import timedelta
from timeblock import application_span

def application_leave_span(leave):
    """ 计算 leaveApplication对象的时间长度
    """
    return application_span(str2dt(leave.start_time),str2dt(leave.end_time),leave.staff.workshift)
    # return timeblock_span(ls)


def dictfy(obj):
    """
    将leaveApplication,avaiLeave对象转换为字典
    """
    if isinstance(obj,LeaveApplication):
        return _dictfy_application(obj)
    elif isinstance(obj,AvaiLeave):
        return _dictfy_availeave(obj)

def _dictfy_availeave(avai):
    if avai.category=='swap_off':
        span={'value':t2h(avai.span),'unit':'hour'}
        used={'value':t2h(avai.used),'unit':'hour'}
    else:
        span={'value':t2day(avai.span),'unit':'day'}
        used={'value':t2day(avai.used),'unit':'day'}
    return {'id':avai.id,
            'empid':avai.staff.employee_id,
            'name':avai.staff.cn_name,
            'category':avai.category,
            'span':span,
            'used':used,
            'start_date':avai.start_date,
            'is_valid':avai.is_valid,
            'note':avai.note
            }         

def _dictfy_application(leave):
    """
    submittedLeave对象的字典表示
    """
    leaders=[]
    check_records=json.loads( leave.check_record)
    for check in check_records:
        leader=get_or_none(StaffInfo,employee_id=check['empid'])
        if leader:
            name=leader.cn_name
        else:
            name=check['empid']
        leaders.append({'name':name,
                        'empid':check['empid'],
                        'status':check['status'],
                        'time':check.get('utime'),
                        'note':check.get('note')})

    return {
        'empid':leave.staff.employee_id,
        'name':leave.staff.cn_name,
        'status':leave.status,
        'id':leave.id,
        'span':application_leave_span(leave),
        'category':leave.category,
        'reason':leave.reason,
        'start_time':leave.start_time,
        'end_time':leave.end_time,
        'create_time': dt2str(timezone.localtime(leave.create_time)),
        'check_record':leaders
        }


# def dictfy_availeave(avai):
    # return {'id':avai.id,
            # 'empid':avai.staff.employee_id,
            # 'name':avai.staff.cn_name,
            # 'category':avai.category,
            # 'span':avai.span,
            # 'used':avai.used,
            # 'sart_date':avai.start_date,
            # 'is_valid':avai.is_valid,
            # 'note':avai.note
    # }


        

    

